﻿using Frame.EntityFrame.IEfRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Frame.EntityFrame.EfRepositories
{
    public class EntityFrameworkRepositoryContext : IEntityFrameworkRepositoryContext
    {
        // ThreadLocal代表线程本地存储，主要相当于一个静态变量
        // 但静态变量在多线程访问时需要显式使用线程同步技术。
        // 使用ThreadLocal变量，每个线程都会一个拷贝，从而避免了线程同步带来的性能开销

        private readonly ThreadLocal<MyDbContext> _localCtx = new ThreadLocal<MyDbContext>(() => new MyDbContext());
        public MyDbContext DbContex
        {
            get { return _localCtx.Value; }
        }

        private readonly Guid _id = Guid.NewGuid();
        public Guid Id
        {
            get { return _id; }
        }

        #region IUnitOfWork Members
        public void Commit()
        {
            var validationError = _localCtx.Value.GetValidationErrors();
            _localCtx.Value.SaveChanges();
        }
        #endregion 
    }
}
